package cn.hcbycloud.code.service.impl;

import cn.hcbycloud.code.mapper.TbDatabaseConfEntityMapper;
import cn.hcbycloud.code.model.GenConfigEntity;
import cn.hcbycloud.code.model.TbDatabaseConfEntity;
import cn.hcbycloud.code.service.SysGeneratorService;
import cn.hcbycloud.code.utils.DataSourceUtils;
import cn.hcbycloud.code.utils.GenUtils;
import cn.hcbycloud.common.core.exception.CustomizeException;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.zip.ZipOutputStream;

/**
 * 数据源操作接口
 *
 * @author gaoheng
 * @date 2020-02-05 17:54:12
 */
@Service("sysGeneratorService")
@AllArgsConstructor
public class SysGeneratorServiceImpl implements SysGeneratorService {

    private final TbDatabaseConfEntityMapper tbDatabaseConfMapper;

    @Override
    public byte[] generatorCode(GenConfigEntity genConfig) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        // 查询表信息
        TbDatabaseConfEntity tbDatabaseConfEntity = tbDatabaseConfMapper.selectById(genConfig.getDbId());
        List<TableInfo> tableInfoList = DataSourceUtils.getTableList(tbDatabaseConfEntity);
        Optional<TableInfo> optional = tableInfoList.stream().filter(tableInfo -> StringUtils.equals(genConfig.getTableName(), tableInfo.getName())).findFirst();
        if (!optional.isPresent()) {
            throw new CustomizeException("未匹配到表");
        }
        TableInfo table = optional.get();

        // 生成代码
        GenUtils.generatorCode(genConfig, table, zip);
        IoUtil.close(zip);
        return outputStream.toByteArray();
    }

    @Override
    public List<TableInfo> getTableList(String id, String tableName) {

        TbDatabaseConfEntity sysDatasourceConf = tbDatabaseConfMapper.selectById(id);

        List<TableInfo> tableInfoList = DataSourceUtils.getTableList(sysDatasourceConf);

        if (StringUtils.isBlank(tableName)) {
            return tableInfoList;
        } else {
            return tableInfoList.stream().filter(tableInfo -> StringUtils.endsWith(tableName, tableInfo.getName())).collect(Collectors.toList());
        }
    }

    @Override
    public List<TbDatabaseConfEntity> getDatabases() {
        return tbDatabaseConfMapper.selectList(null);
    }
}
